package 面试;


import java.util.Arrays;

public class 手写环形队列 {
   public static class CircleQueue {
       private int maxSize;
       private int[] array;
       private int head;
       private int tail;
       private boolean emptyFlag; // full: false; empty: true

       public CircleQueue(int maxSize) {
           this.maxSize = maxSize;
           this.array = new int[maxSize];
           this.head = 0;
           this.tail = 0;
           this.emptyFlag = true;
       }

       public int pop() {
           if ((this.head == this.tail) && this.emptyFlag) {
               throw new RuntimeException("queue is empty");
           } else {
               int val = this.array[this.head];
               this.head = (this.head + 1) % this.maxSize;
               if (this.head == this.tail) {
                   this.emptyFlag = true;
               }
               return val;
           }
       }

       public boolean push(int val) {
           if ((this.head == this.tail) && !this.emptyFlag) {
               throw new RuntimeException("queue is full");
           } else {
                this.array[this.tail] = val;
                this.tail = (this.tail + 1) % this.maxSize;
                if (this.head == this.tail) {
                    this.emptyFlag = false;
                }
           }
           return true;
       }

       public void showQueue() {
           for (int i = 0; i < this.array.length; i++) {
               System.out.print(this.array[i] + " ");
           }
           System.out.println("\n");
       }
   }


    public static void main(String[] args) {
        CircleQueue c = new CircleQueue(5);
        c.push(1);
        c.push(2);
        c.push(3);
        c.push(4);
        c.push(5);
        c.showQueue();
//        c.push(6);
        System.out.println("\n");
        System.out.println(c.pop());
        System.out.println(c.pop());
        System.out.println(c.pop());
        c.push(6);
        System.out.println(c.pop());
        System.out.println(c.pop());
        c.showQueue();
        System.out.println(c.pop());

    }
}
